package com.activiti.web.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;

import common.security.web.util.SecurityUtil;
import common.web.action.CommonAction;
import common.web.vo.Result;

@Controller
@RequestMapping()
public class IndexAction extends CommonAction {

	@Autowired
	private LocaleResolver localeResolver;

	@RequestMapping("/index")
	@ResponseBody
	public Result index(HttpServletResponse response) {
		noCache(response); 
		
		Result res = Result.createResult(SecurityUtil.getUserDetails());
		return res;
	}

	@RequestMapping("/loginFail")
	@ResponseBody
	public Result loginFail(HttpServletRequest request, HttpSession session) {
		AuthenticationException ex = (AuthenticationException) request
				.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
		if (null == ex) {
			ex = (AuthenticationException) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
		}
		return Result.fail(ex.getMessage());
	}

	@RequestMapping("/i18n/{locale}")
	@ResponseBody
	public Result changeLocale(HttpServletRequest request, HttpServletResponse response, @PathVariable String locale)
			throws Exception {
		if (StringUtils.isBlank(locale)) {
			return Result.fail("语言不能为空");
		}
		Locale newLocale = org.springframework.util.StringUtils.parseLocaleString(locale);
		localeResolver.setLocale(request, response, newLocale);
		return Result.SUCCESS;
	}

}
